<?php
/**
 * Created by PhpStorm.
 * User: qch
 * Date: 2015/7/22
 * Time: 18:07
 */

namespace J\Util;

use J\Holder;


/**
 * 本地化类
 *    1、以本地化语言名称(如：zh-cn)字符串作为参数新建本地化类
 *       应用、模块可以通过$language->RegMsg($this)向本地化类注册本地化信息
 *    2、调用 $language->translation($msg) 处理本地化信息
 * 
 * @package J
 */
class Language extends Holder
{
    protected $language = null;

    /**
     * 翻译
     * @param string $msg
     * @return string
     */
    public function translation($msg)
    {
        return array_isset($this->values, $msg, $msg);
    }

    protected function compile($dir, $key = null)
    {
        return $dir . DS . 'i18n' . DS . $this->getLanguage($key) . '.php';
    }

    /**
     * 本地化语言
     * Returns the languages accept by the end user.
     * This is determined by the `Accept-Language` HTTP header.
     *
     * @param string $default
     *
     * @return string
     */
    public static function getAcceptLanguage($default = 'zh-cn')
    {
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $languages = array_keys(parse_accept_header($_SERVER['HTTP_ACCEPT_LANGUAGE']));
            return static::isAcceptableLanguage($languages[0], $default);
        } else {
            return $default;
        }
    }

    protected function getLanguage($default)
    {
        if(!$this->language){
            $this->language = static::getAcceptLanguage($default);
        }

        return $this->language;
    }

    protected static function isAcceptableLanguage($language, $default)
    {
        return  (preg_match('/[a-z-]/i', $language))?$language:$default;
    }


}